<?php

namespace App\Api;

use App\Http\Controllers\Controller;
use App\Models\Appeal;
use App\Models\Wxuser;
use Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use MessageService;

class AppealController extends Controller
{

    public function index(Request $request)
    {
        $category = $request->category;
        $detail = $request->detail;
        $state = $request->state;
        if ($state == 'true') {
            $state = 1;
        }
        if ($state == 'false') {
            $state = 0;
        }

        $appeals = Appeal::when($category, function ($query) use ($category, $detail) {
            $query->where('category', 'like', '%'.$category."%");
        })
            ->when($detail, function ($query) use ($detail) {
                $query->where('detail', 'like', '%'.$detail."%");
            })
            ->where('state', $state)->orderByDesc('id')->paginate(10);
        return $appeals;
    }


    public function show(Appeal $appeal)
    {
        return $appeal;
    }


    public function destroy(Appeal $appeal)
    {
        $appeal->delete();
        return $this->message("删除成功");
    }

    //添加回复
    public function reply(Request $request, Appeal $appeal)
    {
        //接收到发起人wxuser_id
        $wxuser_id = $request->wxuser_id;

        DB::beginTransaction();
        //更新事务状态   该事务已处理
        $appeal->state = true;
        $appeal->save();
        //1、添加回复内容（额外添加发起人的wxuser_id）
        $reply = $appeal->relies()->create($request->input());
        $appeal->refresh();
        //2、更新consultation表，添加回复人（user或者wxuser）
        $replyUser = \Illuminate\Support\Facades\Auth::user();
        $replyUser->replyAppeals()->save($appeal);
        //3、发送通知到发起人（通知该事务已经处理）
        /**
         * 使用TEMPLATE_REMIND_ID
         *    业务内容
         *
         * {{thing1.DATA}}
         * 受理单位
         *
         * {{thing4.DATA}}
         * 时间
         *
         * {{time5.DATA}}
         * 备注
         *
         * {{thing6.DATA}}
         * 业务进度
         *
         * {{thing3.DATA}}
         */
        $wxuser = Wxuser::where("id", $wxuser_id)->first();
        $notifyType = "remind";
        $shortTitle = Str::length($appeal->category) > 10 ?
            (Str::substr($appeal->category, 0, 10)."...") : $appeal->category;

        $shortRemark = Str::length($reply->remark) > 10 ?
            (Str::substr($reply->remark, 0, 10)."...") : $reply->remark;
        //class_basename如果是后台管理员，则Auth::user()为user模型，如果是手机端则为wxuser模型
        $modelType = class_basename(get_class(Auth::user()));
        $replyer = $modelType == 'Wxuser' ? "村干部：".Auth::user()->nickName : "后台管理员";
        $time = \Illuminate\Support\Carbon::now();
        $data =
            [
                "thing1" => ["value" => "{$shortTitle}"],
                "thing4" => ['value' => "{$replyer}"],
                "time5" => ["value" => "{$time}"],
                "thing6" => ["value" => "{$shortRemark}"],
                "thing3" => ["value" => "已完成"]
            ];


        MessageService::send($wxuser, $notifyType, $data);
        //需要将当前$consultation状态改为已处理
        DB::commit();
        return $this->message('回复成功');
    }

    public function record(Request $request, Appeal $appeal)
    {
        return $appeal->relies()->first();
    }
}
